package com.twotwoshop.service.goods.aspect;

import com.twotwoshop.commom.annotation.BrowsingHistoryAnnotation;
import com.twotwoshop.service.goods.service.BrowsingHistoryService;
import com.twotwoshop.util.thread.AppThreadLocalUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class BrowsingHistoryAspect {

    @Autowired
    private BrowsingHistoryService browsingHistoryService;

    @Before("@annotation(com.twotwoshop.commom.annotation.BrowsingHistoryAnnotation)")
    public void logProductView(JoinPoint joinPoint) {


        Object[] args = joinPoint.getArgs();

        // 获取切入点方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 从方法中获取 BrowsingHistoryAnnotation 注解
        BrowsingHistoryAnnotation trackPageView = method.getAnnotation(BrowsingHistoryAnnotation.class);



        if (trackPageView != null) {
            // 获取当前用户ID，假设通过某种方式获取
            Integer userId = AppThreadLocalUtil.getUser().getId();
            if (userId == null) {
                return;
            }

            //获取商品的id
            Long productId = (Long) args[0]; // 商品ID是第一个参数

            try {
                // 记录浏览历史
                browsingHistoryService.addBrowsingHistory(userId, productId);
            } catch (Exception e) {
                throw new RuntimeException(e+"商品浏览历史记录失败");
            }
        }else {
            throw new RuntimeException("商品信息获取成功");
        }


    }
}